#include "stdafx.h"
#include "MessageSystem.h"
#include "InputManager.h"

InputManager::InputManager(void)
{
}

InputManager::~InputManager(void)
{
}

bool InputManager::Init(MessageSystem* message_system)
{
	for (int i = 0; i < 99; i++)
	{
		m_curr_keys[i] = false;
		m_prev_keys[i] = false;
	}

	for (int i = 0; i < 5; i++)
	{
		m_curr_buttons[i] = false;
		m_prev_buttons[i] = false;
	}

	m_message_system = message_system;

	m_message_system->Register(EVT_KEYBOARD, this, &InputManager::OnKeyboard);
	m_message_system->Register(EVT_MOUSEMOVE, this, &InputManager::OnMouseMove);
	m_message_system->Register(EVT_MOUSEBUTTON, this, &InputManager::OnMouseButton);
	m_message_system->Register(EVT_MOUSEWHEEL, this, &InputManager::OnMouseWheel);

	return true;
}

void InputManager::Capture()
{
	//Capture keyboard
	memcpy(m_prev_keys, m_curr_keys, sizeof(m_prev_keys));
	//Capture mouse buttons
	memcpy(m_prev_buttons, m_curr_buttons, sizeof(m_prev_buttons));
}

bool InputManager::KeyDown(EKeyCode key)
{
	if (m_curr_keys[key] == true)
		return true;

	return false;
}
bool InputManager::KeyPressed(EKeyCode key)
{
	if (m_curr_keys[key] == true && m_prev_keys[key] == false)
		return true;

	return false;
}

bool InputManager::KeyReleased(EKeyCode key)
{
	if (m_curr_keys[key] == false && m_prev_keys[key] == true)
		return true;

	return false;
}

bool InputManager::ButtonDown(EMouseButton button)
{
	if (m_curr_buttons[button] == true)
		return true;

	return false;
}

bool InputManager::ButtonPressed(EMouseButton button)
{
	if (m_curr_buttons[button] == true && m_prev_buttons[button] == false)
		return true;

	return false;
}

bool InputManager::ButtonReleased(EMouseButton button)
{
	if (m_curr_buttons[button] == false && m_prev_buttons[button] == true)
		return true;

	return false;
}

void InputManager::OnKeyboard(IEvent *event)
{
	KeyboardEvent* evt = static_cast<KeyboardEvent*>(event);

	for (int i = 0; i < 99; i++)
	{
		if (evt->m_keycode == i)
			m_curr_keys[i] = evt->m_state;
	}
}

void InputManager::OnMouseMove(IEvent *event)
{
	MouseMoveEvent* evt = static_cast<MouseMoveEvent*>(event);

	m_mouse.m_direction.x = m_mouse.m_position.x - evt->m_x;
	m_mouse.m_direction.y = m_mouse.m_position.y - evt->m_y;

	m_mouse.m_position.x = evt->m_x;
	m_mouse.m_position.y = evt->m_y;
}

void InputManager::OnMouseButton(IEvent *event)
{
	MouseButtonEvent* evt = static_cast<MouseButtonEvent*>(event);

	for (int i = 0; i < 5; i++)
	{
		if (evt->m_button == i)
			m_curr_buttons[i] = evt->m_state;
	}
}

void InputManager::OnMouseWheel(IEvent *event)
{
	MouseWheelEvent* evt = static_cast<MouseWheelEvent*>(event);

	m_mouse.m_wheel_position.x = evt->m_x;
	m_mouse.m_wheel_position.y = evt->m_y;
	m_mouse.m_wheel_delta = evt->m_delta;
}